<template>
  <div class="menus">
    <el-row :gutter="16">
      <el-col :span="12">
        <el-card>
          <el-space alignment="center" class="title">
            <span>菜单树</span>
            <span><el-button type="primary" @click="Reset">新建</el-button></span>
          </el-space>
          <div class="content">
            <el-tree :data="tree.data" :props="tree.props" @node-click="handleNodeClick" />
          </div>
        </el-card>
      </el-col>
      <el-col :span="12">
        <el-card>
          <el-space alignment="center" class="title">
            <span>编辑-菜单信息</span>
          </el-space>
          <div class="content">
            <el-form ref="rulesForm" :model="tree.params" :rules="tree.rules" :label-width="80">
              <el-form-item label="菜单名称" required prop="Name">
                <el-input v-model="tree.params.Name" placeholder="菜单名称"></el-input>
              </el-form-item>
              <el-form-item label="对应路由" required prop="Url">
                <el-input v-model="tree.params.Url" placeholder="对应路由"></el-input>
              </el-form-item>
              <el-form-item label="菜单标识" required prop="ClassName">
                <el-input v-model="tree.params.ClassName" placeholder="菜单标识"></el-input>
              </el-form-item>
              <el-form-item label="上级菜单">
                <el-tree-select v-model="tree.params.parentName" :data="selectTree.data" check-strictly
                  placeholder="请选择上级菜单" :render-after-expand="false" :props="tree.props" filterable node-key="Id"
                  :default-expanded-keys="[0]" ref="refSelectTree" @node-click="nodeClick">
                </el-tree-select>
              </el-form-item>
              <el-form-item label="菜单图标">
                <el-input v-model="tree.params.Icon" placeholder="菜单图标" @click="ShowIcons" clearable>
                  <template #prefix>
                    <el-icon class="material-icons">
                      {{ tree.params.Icon }}
                    </el-icon>
                  </template>
                </el-input>
              </el-form-item>
              <el-form-item label="使用方法">
                <el-input type="textarea" v-model="tree.params.Desc" placeholder="使用方法">
                </el-input>
              </el-form-item>
              <el-form-item label="菜单排序"><el-input type="number" v-model="tree.params.Sort" placeholder="菜单排序"></el-input>
              </el-form-item>
              <el-form-item label="是否启用">
                <el-radio-group v-model="tree.params.Enable">
                  <el-radio :label="true">启用</el-radio>
                  <el-radio :label="false">禁用</el-radio>
                </el-radio-group>
              </el-form-item>
            </el-form>
          </div>
          <el-space alignment="center" class="footer">
            <el-button type="primary" @click="Submit(rulesForm)">提交</el-button>
            <el-button type="danger" @click="Delete">删除</el-button>
          </el-space>
        </el-card>
      </el-col>
    </el-row>
    <SelectIconDialog :fromParam="SelectIconParam" :params="tree.params"></SelectIconDialog>
  </div>
</template>

<script lang="ts" setup>
import { ref, reactive, onMounted, onUnmounted } from "vue";
import type { FormInstance } from "element-plus";
import { MenuApiUrl, MenuApi } from "@/api/permession/menu";
import config, { CONFIGS, HOME_URL } from "@/config";
import { PermessionMenu } from "./Def"
import SelectIconDialog from "./SelectIconDialog.vue";
import { useMainLoading } from "@/hooks/useMainLoading"
import { AbortApi } from "@/library/utils/request";
import MessageUti from "@/library/utils/MessageUti"

const { openMainLoading, closeMainLoading } = useMainLoading()

/** 菜单一级名称 */
const MENU_TIELE = CONFIGS.MenuTreeTitle

const rulesForm = ref<FormInstance>();

const defaultParams = reactive<PermessionMenu.FormState>({
  Id: undefined,
  Name: "",
  Url: "",
  ClassName: "",
  ParentId: 0,
  Desc: "",
  Enable: true,
  Icon: "",
  Sort: undefined,
  parentName: "",
});

const tree = reactive<PermessionMenu.TreeState>({
  data: [],
  params: { ...defaultParams },
  rules: {
    Name: [{ required: true, message: '菜单名称不能为空', trigger: "blur" }],
    Url: [{ required: true, message: '对应路由不能为空', trigger: "blur" }],
    ClassName: [
      { required: true, message: '菜单标识不能为空', trigger: "blur" },
    ],
  },
  props: {
    id: "Id",
    children: "Children",
    label: "Name",
    value: "ClassName",
  },
});

const selectTree = reactive<PermessionMenu.SelectTreeState>({
  data: [],
});

const refSelectTree = ref();

// SelectIconDialog 需要的参数数据
const SelectIconParam = reactive<PermessionMenu.SelectIconDialog>({
  modal: false
})

const Reset = () => {
  tree.params = { ...defaultParams };
  rulesForm.value?.resetFields();
};

const handleNodeClick = (data: PermessionMenu.Tree, node: any) => {
  rulesForm.value?.resetFields()
  tree.params = {
    ...data,
    parentName: data.ParentId !== 0 ? node.parent.label : MENU_TIELE
  };
  SetCheckedNode(data.ParentId);
};

const SetCheckedNode = (id: number) => {
  refSelectTree.value.setCurrentKey(id);
};
const nodeClick = (data: PermessionMenu.Tree) => {
  tree.params.ParentId = data.Id;
};

const ShowIcons = () => {
  SelectIconParam.modal = true;
};

const GetData = async () => {
  let param = {
    AppId: config.AppId,
  };

  await MenuApi.SelectMenus(param).then((res) => {
    tree.data = res.Data;

    selectTree.data = [
      {
        Id: 0,
        Name: MENU_TIELE,
        Url: HOME_URL,
        ClassName: "home",
        ParentId: 0,
        Desc: "",
        Enable: true,
        Icon: "home",
        Sort: 0,
        Children: res.Data,
      },
    ];
  });
};

const Submit = async (form: FormInstance | undefined) => {
  if (!form) return;

  await form.validate((valid) => {
    if (valid) {
      const { Id, Sort } = tree.params;
      let dataId = Id ? Id : undefined;
      let params = {
        ...tree.params,
        Id: dataId,
        Sort: Number(Sort)
      }

      const Api = dataId ? MenuApi.UpdateMenu : MenuApi.InsertMenu;
      Api({ ...params }).then((res: any) => {
        CloseReset()
        MessageUti.showSuccess("修改成功")
        GetData();
      });
    }
  });
};

const Delete = async () => {
  const action = await MessageUti.confirm('删除菜单', '是否删除该菜单？')
  if (!action) { return }
  if (tree.params.Id === undefined) { return }

  MenuApi.DeleteMenu({ Id: tree.params.Id }).then((res) => {
    MessageUti.showSuccess('删除成功');
    GetData();
    Reset()
  });
};

const CloseReset = () => {
  tree.params = { ...defaultParams }
}

onMounted(async () => {
  openMainLoading()
  await GetData()
  closeMainLoading()
})

onUnmounted(() => {
  AbortApi(MenuApiUrl.SelectMenus)
})

</script>

<style lang="scss" scoped>
.menus {
  padding: 16px;
  color: #666;

  .title {
    display: flex;
    justify-content: space-between;
    border-bottom: 1px solid #eee;
    line-height: 34px;
  }

  .content {
    padding: 25px;

  }

  .footer {
    display: flex;
    justify-content: flex-end;
  }
}
</style>